﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Mime;
using System.Text;
using System.Xml;

namespace SimpleHttpServer.GuestBook
{
    public class XmlGuestBook : IGuestBook
    {
        private string _guestBookFileName = Path.Combine(CommonHelper.AppPath, "GuestBook.xml");


        public void Add(GuestBookEntry guestBookEntry)
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(_guestBookFileName);

            XmlNode xRoot = xmlDoc.DocumentElement;

            XmlNode xmlEntry = xmlDoc.CreateNode(XmlNodeType.Element, "message", null);

            XmlAttribute attrUsername = xmlDoc.CreateAttribute("user");
            XmlAttribute attrText = xmlDoc.CreateAttribute("text");

            attrUsername.Value = guestBookEntry.UserName;
            attrText.Value = guestBookEntry.Message;

            xmlEntry.Attributes.Append(attrUsername);
            xmlEntry.Attributes.Append(attrText);

            xRoot.AppendChild(xmlEntry);

            xmlDoc.Save(_guestBookFileName);
            
        }



        public IEnumerable<GuestBookEntry> FindAll()
        {
            List<GuestBookEntry> entries = new List<GuestBookEntry>();

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(_guestBookFileName);

            XmlNode xRoot = xmlDoc.DocumentElement;


            foreach (XmlNode node in xRoot.ChildNodes)
            {
                string userName = node.Attributes["user"].Value;
                string text = node.Attributes["text"].Value;

                entries.Add(new GuestBookEntry(userName, text));
            }

            return entries;

        }
    }
}
